import React, { useState, useRef, useEffect } from 'react';
import { useFormInput } from '../hooks/useFormInput';

function TodoForm({ addTodo }) {
  const todoInput = useFormInput('');
  const [error, setError] = useState('');
  const inputRef = useRef(null);
  
  // 使用 useEffect 和 useRef 自动聚焦输入框
  useEffect(() => {
    inputRef.current.focus();
  }, []);
  
  const handleSubmit = (e) => {
    e.preventDefault();
    
    // 表单验证
    if (todoInput.value.trim() === '') {
      setError('待办事项不能为空');
      return;
    }
    
    if (todoInput.value.length > 50) {
      setError('待办事项不能超过50个字符');
      return;
    }
    
    // 验证通过，添加待办事项
    addTodo(todoInput.value);
    todoInput.reset();
    setError('');
  };

  return (
    <form className="todo-form" onSubmit={handleSubmit}>
      <div className="form-group">
        <input
          ref={inputRef}
          type="text"
          className={`todo-input ${error ? 'input-error' : ''}`}
          placeholder="添加新的待办事项..."
          value={todoInput.value}
          onChange={todoInput.onChange}
        />
        {error && <div className="error-message">{error}</div>}
      </div>
      <button type="submit" className="todo-button">添加</button>
    </form>
  );
}

export default TodoForm; 